/*
 * Copyright(c) 2020 Jesse Kuang  <jkuang@21cn.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *  * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <errno.h>
#ifdef	__x86_64__
#include <cpuid.h>
#endif
#include "ecc.h"
#include "curve_const.hpp"
#include "curve_impl.hpp"

//#pragma GCC push_options
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC pop_options


using namespace vli;
using namespace ecc;

extern "C" void vli_sm2p_mod(u64 *result, const u64 *left, const bool carry)
{
	sm2p_mod(result, left, carry);
}

extern "C" void vli_sm2p_reduction(u64 *result, const u64 *y)
{
	sm2p_reduction(result, y);
}

extern "C" void vli_sm2p_mod_mult(u64 *result, const u64 *x, const u64 *y)
{
	sm2p_mult(result, x, y);
}

extern "C" void mont_sm2_mod_mult_n(u64 *result, const u64 *x, const u64 *y)
{
	u64	xp[4];
	u64	yp[4];
	u64	r[4];
	mont_mult<4,sm2_n_k0>(xp, x, sm2_n_rr, sm2_n);
	mont_mult<4,sm2_n_k0>(yp, y, sm2_n_rr, sm2_n);
	mont_mult<4,sm2_n_k0>(r, xp, yp, sm2_n);
	mont_reduction<4,sm2_n_k0>(result, r, sm2_n);
}

extern "C" void to_mont_sm2_n(u64 *result, const u64 *x)
{
	mont_mult<4,sm2_n_k0>(result, x, sm2_n_rr, sm2_n);
}


extern "C" void vli_sm2p_sqr(u64 *result, const u64 *x)
{
	sm2p_sqrN(result, x);
}

extern "C" void vli_mod_inv(u64 *result, const u64 *input, const u64 *mod)
{
	vli_mod_inv<4>(result, input, mod);
}
